//
//  LoginNetManage.swift
//  YUANSHI
//
//  Created by pro on 2020/1/8.
//  Copyright © 2020 wangbin. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON

/// 推荐商家列表
let loginUrl = "/appapi.php?c=Login&a=sendCode"

enum loginNetApi {
    case LoginUrlMethod(phone : String,password : String)
}

extension loginNetApi : TargetType{
    
    var baseURL: URL {
        switch self {
        default:
            return URL(string: personDataModel.httpsUrl)!
        }
    }
    
    var path: String {
        switch self {
        case .LoginUrlMethod:
            return loginUrl
        }
    }
    
    var method: Moya.Method{
        switch self {
        case .LoginUrlMethod:
            return .post
        }
    }
    
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
//    "Device-Id" = "266BAAA1-A236-4CDC-BC82-6DEB36C6C20F";
//    client = 1;
//    code = "";
//    passwd = 123456789;
//    phone = 18255153024;
//    "phone_country_type" = 86;
//    "spread_code" = "";
    var task: Task {
        var parmeters:[String:Any] = [:]
        switch self {
        case .LoginUrlMethod(let phone, let password):
//            "Device-Id" = "266BAAA1-A236-4CDC-BC82-6DEB36C6C20F";
            parmeters = [
            "device":"iPhone",
            "appid":0,
            "categoryId":-2,
            "channel":"ios-b1",
            "code":"43_310000_3100",
            "includeActivity":true,
            "includeSpecial":true,
            "network":"WIFI",
            "operator":3,
            "pullToRefresh":true,
            "scale":3,
            "uid":0,
            "version":"6.5.3",
            "xt": Int32(Date().timeIntervalSince1970),
            "deviceId": UIDevice.current.identifierForVendor!.uuidString]
            return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)

        }
    }
    
    var headers: [String : String]? {
//        return ["EACSESSION":logoinMode.User.session_id]
        return ["EACSESSION":""];
    }
    
    
    
    /// 网络错误处理
    ///
    /// - Parameter timeInterval: 超时时间设置
    /// - Returns: return value description
    public static func hFApiProvider(timeInterval:TimeInterval  = 15) -> MoyaProvider<loginNetApi> {
        return MoyaProvider<loginNetApi>(
            requestClosure: { (endPoint, closure) in
                do {
                    var urlRequest = try endPoint.urlRequest()
                    urlRequest.timeoutInterval = timeInterval;
                    closure(.success(urlRequest))
                } catch MoyaError.requestMapping(let url) {
                    closure(.failure(MoyaError.requestMapping(url)))
                } catch MoyaError.parameterEncoding(let error) {
                    closure(.failure(MoyaError.parameterEncoding(error)))
                } catch {
                    closure(.failure(MoyaError.underlying(error, nil)))
                }
        })
    }

    
    
    
}
struct loginNetWork {
    public static func request(target: loginNetApi,
                               success successCallback: @escaping (JSON) -> Void,
                               error errorCallback: @escaping (Int) -> Void,
                               failure failureCallback: @escaping (MoyaError) -> Void) {
        
        let Provider = loginNetApi.hFApiProvider()
        
        Provider.request(target) { result in
//            print(result);
            
            
            switch result {
            case let .success(response):
                do {
//                    let jso = JSON(data: response)
//                    print(response)
                    //                    过滤状态码为请求成功的filterSuccessfulStatusCodes
                    let json = try JSON(response.filterSuccessfulStatusCodes().mapJSON())
                    successCallback(json)
                }
                catch let error {
                    errorCallback((error as! MoyaError).response!.statusCode)
                }
            case let .failure(error):
                failureCallback(error)
            }
        }
    }
    
    
    
}
